﻿using AutoMapper;
using Durian.API.Application.Commands.Assembly;
using IMES.Common.Domain.DurianModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using MediatR;
using static FreeSql.Internal.GlobalFilter;

namespace Durian.API.Application.Commands.Mission
{
    public class MissionDeleteHandler : IRequestHandler<MissionDeleteCommand, Result>
    {
        private readonly IMapper mapper;
        private readonly ILogger<MissionSelectHandler> logger;
        private readonly IBaseRepositorys<ProcessManagement> processManagementRepository;
        private readonly IBaseRepositorys<Tasks> tasksRepository;

        public MissionDeleteHandler(IMapper mapper, ILogger<MissionSelectHandler> logger, IBaseRepositorys<ProcessManagement> processManagementRepository, IBaseRepositorys<Tasks> tasksRepository)
        {
            this.mapper = mapper;
            this.logger = logger;
            this.processManagementRepository = processManagementRepository;
            this.tasksRepository = tasksRepository;
        }

        /// <summary>
        /// 批量删除任务信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(MissionDeleteCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var result = new Result();
                string[] strings = request.Ids.Split(',');
                foreach (var item in strings)
                {
                    var info = tasksRepository.GetAll().FirstOrDefault(c => c.TasksId == Convert.ToInt32(item));
                    if (info == null)
                    {
                        // 处理未找到的情况，例如记录日志或设置result的Code
                        continue;
                    }
                    info.Deletes = true;
                    info.DeleteTime = DateTime.Now;
                    //result.Code += info.Code;
                    result.Code += tasksRepository.Update(info);
                }
                logger.LogInformation("批量删除任务信息方法调用成功");
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError("批量删除任务信息方法调用出错" + ex);
                throw;
            }
        }
    }
}
